package cn.cosmosx.base.security.service;

import cn.cosmosx.base.security.entity.SecurityUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 自定义认证提供者
 * <p>
 * 登录认证时会走该类
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        final String username = authentication.getName();
        final String password = authentication.getCredentials().toString();
        SecurityUserVo userDetails = customUserDetailsService.loadUserByUsername(username);
        if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
            // 认证成功，关键信息UsernamePasswordAuthenticationToken 下的 super.setAuthenticated(true);
            return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        }
        throw new BadCredentialsException("用户名密码错误");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}
